{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Use Case for Prompt using footnote format\n",
    "\n",
    "- Author: [Jinu Cho](https://github.com/jinucho)\n",
    "- Peer Review: \n",
    "- This is a part of [LangChain Open Tutorial](https://github.com/LangChain-OpenTutorial/LangChain-OpenTutorial)\n",
    "\n",
    "## Overview\n",
    "\n",
    "This tutorial is an improved prompt version of the **MakeReport-Using-RAG-Websearching-Imagegeneration-Agent**\n",
    "\n",
    "For more details, please refer to [MakeReport-Using-RAG-Websearching-Imagegeneration-Agent](https://colab.research.google.com/github/LangChain-OpenTutorial/LangChain-OpenTutorial/blob/main/15-Agents/09-MakeReport-Using-RAG-Websearching-Imagegeneration-Agent.ipynb)\n",
    "\n",
    "---"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Environment Setup\n",
    "\n",
    "Set up the environment. You may refer to [Environment Setup](https://wikidocs.net/257836) for more details.\n",
    "\n",
    "**[Note]**\n",
    "- ```langchain-opentutorial``` is a package that provides a set of easy-to-use environment setup, useful functions and utilities for tutorials. \n",
    "- You can checkout the [```langchain-opentutorial```](https://github.com/LangChain-OpenTutorial/langchain-opentutorial-pypi) for more details."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {},
   "outputs": [],
   "source": [
    "%%capture --no-stderr\n",
    "%pip install langchain-opentutorial"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "metadata": {},
   "outputs": [
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "\n",
      "\u001b[1m[\u001b[0m\u001b[34;49mnotice\u001b[0m\u001b[1;39;49m]\u001b[0m\u001b[39;49m A new release of pip is available: \u001b[0m\u001b[31;49m24.3.1\u001b[0m\u001b[39;49m -> \u001b[0m\u001b[32;49m25.0\u001b[0m\n",
      "\u001b[1m[\u001b[0m\u001b[34;49mnotice\u001b[0m\u001b[1;39;49m]\u001b[0m\u001b[39;49m To update, run: \u001b[0m\u001b[32;49mpip install --upgrade pip\u001b[0m\n"
     ]
    }
   ],
   "source": [
    "# Install required packages\n",
    "from langchain_opentutorial import package\n",
    "\n",
    "package.install(\n",
    "    [\n",
    "        \"langsmith\",\n",
    "        \"langchain\",\n",
    "        \"langchain_openai\",\n",
    "        \"langchain_core\",\n",
    "        \"langchain_community\",\n",
    "        \"langchain_text_splitters\",\n",
    "        \"faiss-cpu\",\n",
    "        \"pymupdf\",\n",
    "        \"pydantic\",\n",
    "    ],\n",
    "    verbose=False,\n",
    "    upgrade=False,\n",
    ")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Environment variables have been set successfully.\n"
     ]
    }
   ],
   "source": [
    "# Set environment variables\n",
    "from langchain_opentutorial import set_env\n",
    "\n",
    "set_env(\n",
    "    {\n",
    "        \"OPENAI_API_KEY\": \"\",\n",
    "        \"LANGCHAIN_API_KEY\": \"\",\n",
    "        \"LANGCHAIN_TRACING_V2\": \"true\",\n",
    "        \"LANGCHAIN_ENDPOINT\": \"https://api.smith.langchain.com\",\n",
    "        \"LANGCHAIN_PROJECT\": \"Prompt-using-footnote-format\",\n",
    "        \"TAVILY_API_KEY\": \"\",\n",
    "    }\n",
    ")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "You can alternatively set ```OPENAI_API_KEY``` in ```.env``` file and load it. \n",
    "\n",
    "[Note] This is not necessary if you've already set ```OPENAI_API_KEY``` in previous steps."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "True"
      ]
     },
     "execution_count": 4,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "from dotenv import load_dotenv\n",
    "\n",
    "load_dotenv(override=True)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "metadata": {},
   "outputs": [],
   "source": [
    "from langchain_community.tools.tavily_search import TavilySearchResults\n",
    "\n",
    "# Create an instance of TavilySearchResults with k=6 for retrieving up to 6 search results\n",
    "search_tool = TavilySearchResults(k=6)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Document Used for Practice  \n",
    "\n",
    "**Tesla's Revenue Forecast Based on Business Model and Financial Statement Analysis**  \n",
    "\n",
    "**Author:** Chenhao Fang  \n",
    "**Institution:** Intelligent Accounting Management Institute, Guangdong University of Finance and Economics  \n",
    "**Link:** [Tesla's revenue forecast base on business model and financial statement analysis ](https://www.shs-conferences.org/articles/shsconf/pdf/2024/01/shsconf_icdeba2023_02022.pdf)  \n",
    "**File Name:** shsconf_icdeba2023_02022.pdf\n",
    "\n",
    "_Please copy the downloaded file to the data folder for practice._  \n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "File 'shsconf_icdeba2023_02022.pdf' already exists. Skipping download.\n"
     ]
    }
   ],
   "source": [
    "import os\n",
    "import requests\n",
    "\n",
    "# PDF URL\n",
    "url = \"https://www.shs-conferences.org/articles/shsconf/pdf/2024/01/shsconf_icdeba2023_02022.pdf\"\n",
    "\n",
    "# File name to save\n",
    "file_name = \"shsconf_icdeba2023_02022.pdf\"\n",
    "\n",
    "# Custom headers to mimic a browser request\n",
    "headers = {\n",
    "    \"User-Agent\": \"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36\",\n",
    "    \"Referer\": \"https://www.shs-conferences.org/\",\n",
    "}\n",
    "\n",
    "# Check if the file already exists\n",
    "if not os.path.exists(file_name):\n",
    "    # Send request with headers\n",
    "    response = requests.get(url, headers=headers, stream=True)\n",
    "    if response.status_code == 200:\n",
    "        with open(file_name, \"wb\") as pdf_file:\n",
    "            for chunk in response.iter_content(1024):\n",
    "                pdf_file.write(chunk)\n",
    "        print(f\"PDF has been saved as '{file_name}'.\")\n",
    "    else:\n",
    "        print(f\"Failed to download PDF: {response.status_code}\")\n",
    "else:\n",
    "    print(f\"File '{file_name}' already exists. Skipping download.\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "metadata": {},
   "outputs": [],
   "source": [
    "from langchain_text_splitters import RecursiveCharacterTextSplitter\n",
    "from langchain_community.vectorstores import FAISS\n",
    "from langchain_openai import OpenAIEmbeddings\n",
    "from langchain_community.document_loaders import PyMuPDFLoader\n",
    "\n",
    "# Example PDF file path (modify according to your environment)\n",
    "pdf_file_path = \"shsconf_icdeba2023_02022.pdf\"\n",
    "\n",
    "# Load the PDF using PyMuPDFLoader\n",
    "loader = PyMuPDFLoader(pdf_file_path)\n",
    "\n",
    "# Split text into smaller chunks\n",
    "text_splitter = RecursiveCharacterTextSplitter(chunk_size=1000, chunk_overlap=100)\n",
    "split_docs = loader.load_and_split(text_splitter)\n",
    "\n",
    "# Create FAISS VectorStore\n",
    "vector = FAISS.from_documents(split_docs, OpenAIEmbeddings())\n",
    "\n",
    "# Create a retriever from the VectorStore\n",
    "retriever = vector.as_retriever()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 8,
   "metadata": {},
   "outputs": [],
   "source": [
    "from langchain_core.tools.retriever import create_retriever_tool\n",
    "from langchain_core.prompts import PromptTemplate\n",
    "\n",
    "document_prompt = PromptTemplate.from_template(\n",
    "    \"<document>\\n\"\n",
    "    \"  <content>{page_content}</content>\\n\"\n",
    "    \"  <page>{page}</page>\\n\"\n",
    "    \"  <source>{source}</source>\\n\"\n",
    "    \"</document>\"\n",
    ")\n",
    "\n",
    "retriever_tool = create_retriever_tool(\n",
    "    retriever,\n",
    "    name=\"pdf_search\",\n",
    "    description=\"use this tool to search for information in Tesla PDF file\",\n",
    "    document_prompt=document_prompt,\n",
    ")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 9,
   "metadata": {},
   "outputs": [],
   "source": [
    "from langchain_community.utilities.dalle_image_generator import DallEAPIWrapper\n",
    "from langchain_core.tools import tool\n",
    "\n",
    "dalle = DallEAPIWrapper(\n",
    "    model=\"dall-e-3\",  # DALL·E model version\n",
    "    size=\"1024x1024\",  # Image size\n",
    "    quality=\"standard\",  # Image quality\n",
    "    n=1,  # Number of images to generate\n",
    ")\n",
    "\n",
    "\n",
    "@tool\n",
    "def dalle_tool(query: str) -> str:\n",
    "    \"\"\"Use this tool to generate an image from text\"\"\"\n",
    "    return dalle.run(query)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 10,
   "metadata": {},
   "outputs": [],
   "source": [
    "from langchain_community.agent_toolkits import FileManagementToolkit\n",
    "\n",
    "working_directory = \"tmp\"\n",
    "\n",
    "file_tools = FileManagementToolkit(\n",
    "    root_dir=str(working_directory),\n",
    "    selected_tools=[\"write_file\", \"read_file\", \"list_directory\"],\n",
    ").get_tools()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 11,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "[WriteFileTool(root_dir='tmp'),\n",
       " ReadFileTool(root_dir='tmp'),\n",
       " ListDirectoryTool(root_dir='tmp'),\n",
       " Tool(name='pdf_search', description='use this tool to search for information in Tesla PDF file', args_schema=<class 'langchain_core.tools.retriever.RetrieverInput'>, func=functools.partial(<function _get_relevant_documents at 0x144f69120>, retriever=VectorStoreRetriever(tags=['FAISS', 'OpenAIEmbeddings'], vectorstore=<langchain_community.vectorstores.faiss.FAISS object at 0x16b638980>, search_kwargs={}), document_prompt=PromptTemplate(input_variables=['page', 'page_content', 'source'], input_types={}, partial_variables={}, template='<document>\\n  <content>{page_content}</content>\\n  <page>{page}</page>\\n  <source>{source}</source>\\n</document>'), document_separator='\\n\\n'), coroutine=functools.partial(<function _aget_relevant_documents at 0x145402fc0>, retriever=VectorStoreRetriever(tags=['FAISS', 'OpenAIEmbeddings'], vectorstore=<langchain_community.vectorstores.faiss.FAISS object at 0x16b638980>, search_kwargs={}), document_prompt=PromptTemplate(input_variables=['page', 'page_content', 'source'], input_types={}, partial_variables={}, template='<document>\\n  <content>{page_content}</content>\\n  <page>{page}</page>\\n  <source>{source}</source>\\n</document>'), document_separator='\\n\\n')),\n",
       " TavilySearchResults(api_wrapper=TavilySearchAPIWrapper(tavily_api_key=SecretStr('**********'))),\n",
       " StructuredTool(name='dalle_tool', description='Use this tool to generate an image from text', args_schema=<class 'langchain_core.utils.pydantic.dalle_tool'>, func=<function dalle_tool at 0x168411da0>)]"
      ]
     },
     "execution_count": 11,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "tools = file_tools + [\n",
    "    retriever_tool,  # PDF search (RAG)\n",
    "    search_tool,  # Web search\n",
    "    dalle_tool,  # Image generation\n",
    "]\n",
    "tools"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 12,
   "metadata": {},
   "outputs": [],
   "source": [
    "from langchain.agents import AgentExecutor, create_tool_calling_agent\n",
    "from langchain_community.chat_message_histories import ChatMessageHistory\n",
    "from langchain_core.prompts import ChatPromptTemplate, PromptTemplate, load_prompt\n",
    "from langchain_core.prompts.chat import (\n",
    "    ChatPromptTemplate,\n",
    "    HumanMessagePromptTemplate,\n",
    "    MessagesPlaceholder,\n",
    "    SystemMessagePromptTemplate,\n",
    ")\n",
    "from langchain_core.runnables.history import RunnableWithMessageHistory\n",
    "from langchain_openai import ChatOpenAI\n",
    "\n",
    "store = {}\n",
    "\n",
    "# Load the YAML file (MakeReport.yaml)\n",
    "yaml_prompt = load_prompt(\"MakeReport.yaml\")\n",
    "\n",
    "# Create a ChatPromptTemplate using the template from the YAML file as a system message,\n",
    "# and pass along the metadata as defined in the YAML.\n",
    "prompt = ChatPromptTemplate(\n",
    "    messages=[\n",
    "        SystemMessagePromptTemplate(\n",
    "            prompt=PromptTemplate(\n",
    "                template=yaml_prompt.template,\n",
    "                input_variables=yaml_prompt.input_variables,\n",
    "                partial_variables=yaml_prompt.partial_variables,\n",
    "                input_types=getattr(yaml_prompt, \"input_types\", {}),\n",
    "            )\n",
    "        ),\n",
    "        # Include placeholders defined in the YAML file\n",
    "        MessagesPlaceholder(variable_name=\"chat_history\", optional=True),\n",
    "        MessagesPlaceholder(variable_name=\"agent_scratchpad\", optional=True),\n",
    "        # Human message: create a template that only accepts user input\n",
    "        HumanMessagePromptTemplate(\n",
    "            prompt=PromptTemplate(template=\"{input}\", input_variables=[\"input\"])\n",
    "        ),\n",
    "    ],\n",
    "    # Pass along the metadata defined in the YAML file\n",
    "    input_variables=yaml_prompt.input_variables,\n",
    "    optional_variables=yaml_prompt.optional_variables,\n",
    "    partial_variables=yaml_prompt.partial_variables,\n",
    "    input_types=getattr(yaml_prompt, \"input_types\", {}),\n",
    ")\n",
    "\n",
    "\n",
    "llm = ChatOpenAI(model=\"gpt-4o\", temperature=0)\n",
    "\n",
    "agent = create_tool_calling_agent(llm, tools, prompt)\n",
    "\n",
    "agent_executor = AgentExecutor(\n",
    "    agent=agent,\n",
    "    tools=tools,\n",
    "    verbose=False,\n",
    "    handle_parsing_errors=True,\n",
    ")\n",
    "\n",
    "\n",
    "def get_session_history(session_ids):\n",
    "    if session_ids not in store:\n",
    "        store[session_ids] = ChatMessageHistory()\n",
    "    return store[session_ids]\n",
    "\n",
    "\n",
    "agent_with_chat_history = RunnableWithMessageHistory(\n",
    "    agent_executor,\n",
    "    get_session_history,\n",
    "    input_messages_key=\"input\",\n",
    "    history_messages_key=\"chat_history\",\n",
    ")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 13,
   "metadata": {},
   "outputs": [],
   "source": [
    "from langchain_core.agents import AgentAction, AgentStep\n",
    "from langchain.agents.output_parsers.tools import ToolAgentAction\n",
    "\n",
    "from typing import Any, Dict, List, Callable\n",
    "from dataclasses import dataclass\n",
    "\n",
    "\n",
    "# Callback for tool calls\n",
    "def tool_callback(tool) -> None:\n",
    "    print(\"[Tool Called]\")\n",
    "    print(f\"Tool: {tool.get('tool')}\")\n",
    "    if tool_input := tool.get(\"tool_input\"):\n",
    "        for k, v in tool_input.items():\n",
    "            print(f\"{k}: {v}\")\n",
    "    print(f\"Log: {tool.get('log')}\")\n",
    "\n",
    "\n",
    "# Callback for observations\n",
    "def observation_callback(observation) -> None:\n",
    "    print(\"[Observation]\")\n",
    "    print(f\"Observation: {observation.get('observation')}\")\n",
    "\n",
    "\n",
    "# Callback for final result\n",
    "def result_callback(result: str) -> None:\n",
    "    print(\"[Final Answer]\")\n",
    "    print(result)\n",
    "\n",
    "\n",
    "@dataclass\n",
    "class AgentCallbacks:\n",
    "    tool_callback: Callable[[Dict[str, Any]], None] = tool_callback\n",
    "    observation_callback: Callable[[Dict[str, Any]], None] = observation_callback\n",
    "    result_callback: Callable[[str], None] = result_callback\n",
    "\n",
    "\n",
    "class AgentStreamParser:\n",
    "    \"\"\"\n",
    "    A class to parse and handle streaming output from the agent.\n",
    "    \"\"\"\n",
    "\n",
    "    def __init__(self, callbacks: AgentCallbacks = AgentCallbacks()):\n",
    "        \"\"\"Initialize the AgentStreamParser with custom callbacks.\"\"\"\n",
    "        self.callbacks = callbacks\n",
    "        self.output = None\n",
    "\n",
    "    def process_agent_steps(self, step: Dict[str, Any]) -> None:\n",
    "        \"\"\"Process each step in the agent's output.\"\"\"\n",
    "        if \"actions\" in step:\n",
    "            self._process_actions(step[\"actions\"])\n",
    "        elif \"steps\" in step:\n",
    "            self._process_observations(step[\"steps\"])\n",
    "        elif \"output\" in step:\n",
    "            self._process_result(step[\"output\"])\n",
    "\n",
    "    def _process_actions(self, actions: List[Any]) -> None:\n",
    "        \"\"\"Handle each tool action detected.\"\"\"\n",
    "        for action in actions:\n",
    "            if isinstance(action, (AgentAction, ToolAgentAction)) and hasattr(\n",
    "                action, \"tool\"\n",
    "            ):\n",
    "                self._process_tool_call(action)\n",
    "\n",
    "    def _process_tool_call(self, action: Any) -> None:\n",
    "        \"\"\"Handle logic for a single tool call.\"\"\"\n",
    "        tool_action = {\n",
    "            \"tool\": getattr(action, \"tool\", None),\n",
    "            \"tool_input\": getattr(action, \"tool_input\", None),\n",
    "            \"log\": getattr(action, \"log\", None),\n",
    "        }\n",
    "        self.callbacks.tool_callback(tool_action)\n",
    "\n",
    "    def _process_observations(self, observations: List[Any]) -> None:\n",
    "        \"\"\"Handle the observations produced by the agent.\"\"\"\n",
    "        for observation in observations:\n",
    "            observation_dict = {}\n",
    "            if isinstance(observation, AgentStep):\n",
    "                observation_dict[\"observation\"] = getattr(\n",
    "                    observation, \"observation\", None\n",
    "                )\n",
    "            self.callbacks.observation_callback(observation_dict)\n",
    "\n",
    "    def _process_result(self, result: str) -> None:\n",
    "        \"\"\"Handle the final result from the agent.\"\"\"\n",
    "        self.callbacks.result_callback(result)\n",
    "        self.output = result\n",
    "\n",
    "\n",
    "# Create the stream parser\n",
    "agent_stream_parser = AgentStreamParser()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 14,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "=== Agent Execution Result ===\n",
      "[Tool Called]\n",
      "Tool: pdf_search\n",
      "query: Tesla financial information and revenue outlook 2024-2025\n",
      "Log: \n",
      "Invoking: `pdf_search` with `{'query': 'Tesla financial information and revenue outlook 2024-2025'}`\n",
      "\n",
      "\n",
      "\n",
      "[Observation]\n",
      "Observation: <document>\n",
      "  <content>dollars, +18% year-on-year. Assuming a vehicle price of \n",
      "$45,000 and $43,000 in 24 and '25, by 2025, the revenue \n",
      "from electric vehicle sales will be about $130 billion, +80% \n",
      "from '22. All of this is based on an analysis of Tesla's \n",
      "existing assets and liabilities and business model. This study \n",
      "predicts Tesla's income in the next few years. It is certain \n",
      "that Tesla's income will continue to grow in the next few \n",
      "years, which may help some investors related to Tesla in \n",
      "terms of investment. However, since Tesla discloses less \n",
      "economic information to the outside world, and the research \n",
      "method of this paper is relatively simple, the information \n",
      "that can be provided is limited. In future studies, researchers \n",
      "can use more diverse and accurate methods to predict \n",
      "Tesla's income. \n",
      "References \n",
      "1. Y. Liu, Jiangsu Comm Forum 369, 7 (2015) \n",
      "2. F. Han, Beijing Uni Posts Telec, (2018) \n",
      "3. S. Yan, Modern Busi 589, 36 (2020) \n",
      "4. M. Wang, Shandong Uni, (2021)</content>\n",
      "  <page>4</page>\n",
      "  <source>shsconf_icdeba2023_02022.pdf</source>\n",
      "</document>\n",
      "\n",
      "<document>\n",
      "  <content>strategy of the company's development. Similarly, gross \n",
      "margin will fluctuate with changes in capacity, sales volume, \n",
      "scale effect, and amortized production costs.. \n",
      "In 2020, Tesla produced a total of 1,369,600 vehicles \n",
      "worldwide and delivered a total of 1,313,900 vehicles, +40% \n",
      "year-on-year, slightly below the 50% growth target set at the \n",
      "beginning of 22 years. \n",
      "Number of vehicle sales are expected to reach 1.8 \n",
      "million units in 23 years, approximately +35% y/y. \n",
      "Combined with a forecast for the number of Tesla electric \n",
      "vehicle deliveries, we can predict Tesla's future revenue. \n",
      "6 Conclusion \n",
      "Fig. 1. Revenue forecast. \n",
      "Figure 1 shows Tesla's future revenue. So, Tesla's forecast \n",
      "profit is $71.4 billion in 2023, $84.6 billion in 2024, and \n",
      "$131.2 billion in 2025. Based on the average price of Tesla \n",
      "in 23 years of $47,000, the revenue of the electric vehicle \n",
      "business in 23 years is estimated to be 84.6 billion US \n",
      "dollars, +18% year-on-year. Assuming a vehicle price of</content>\n",
      "  <page>4</page>\n",
      "  <source>shsconf_icdeba2023_02022.pdf</source>\n",
      "</document>\n",
      "\n",
      "<document>\n",
      "  <content>Corresponding author: 1910741120@mail.sit.edu.cn \n",
      "year. With a penetration rate of 2.1%, the global sales \n",
      "volume of automobiles in 2018 exceeded 2 million. China, \n",
      "the USA, Germany, France, Sweden, Japan, and other \n",
      "nations account for a large portion of the world's new energy \n",
      "market [3]. If you want to predict the future development of \n",
      "the electric vehicle industry, you can speculate by predicting \n",
      "Tesla's future financial situation. This study hopes to \n",
      "provide some insight into the future forecast of the electric \n",
      "vehicle industry by predicting Tesla's future financial \n",
      "situation. In this research, common-size financial statements \n",
      "and ratio analysis are used. Start with Tesla's basic financial \n",
      "situation, then analyze Tesla's business model, and finally \n",
      "predict Tesla's future financial situation. \n",
      "2 An analysis of Tesla's underlying \n",
      "financial position \n",
      "2.1 Assets \n",
      " \n",
      " \n",
      " \n",
      "SHS Web of Conferences 181, 02022 (2024)\t\n",
      "https://doi.org/10.1051/shsconf/202418102022\n",
      "ICDEBA 2023</content>\n",
      "  <page>0</page>\n",
      "  <source>shsconf_icdeba2023_02022.pdf</source>\n",
      "</document>\n",
      "\n",
      "<document>\n",
      "  <content>Tesla's revenue forecast base on business model and financial \n",
      "statement analysis \n",
      "Chenhao Fang   \n",
      "Intelligent Accounting Management Institute, Guangdong University of Finance and Economics, 510200 Guangzhou, China \n",
      "Abstract. With the rapid development of the electric vehicle industry, Tesla, as the benchmark of this industry, \n",
      "has been studied by many companies in the same industry and investors outside the industry. Based on Tesla's \n",
      "financial reports in recent years and news about Tesla, Tesla's assets, liabilities, and owner's equity are analyzed \n",
      "to analyze Tesla's basic financial situation, from this, it can be concluded that Tesla's asset-liability ratio and \n",
      "other financial trends have changed in recent years. Then analyze Tesla's business model from the aspects of \n",
      "corporate positioning, business type, and profit model, so, in recent years, Tesla's main profit models, income</content>\n",
      "  <page>0</page>\n",
      "  <source>shsconf_icdeba2023_02022.pdf</source>\n",
      "</document>\n",
      "[Tool Called]\n",
      "Tool: write_file\n",
      "file_path: report.md\n",
      "text: ## Summary of Tesla's Financial Information and Revenue Outlook\n",
      "\n",
      "- Tesla's revenue from electric vehicle sales is projected to reach about $130 billion by 2025, an 80% increase from 2022[^1].\n",
      "- The forecasted profit for Tesla is $71.4 billion in 2023, $84.6 billion in 2024, and $131.2 billion in 2025[^2].\n",
      "- The number of vehicle sales is expected to reach 1.8 million units in 2023, approximately a 35% year-on-year increase[^2].\n",
      "- Tesla's business model and financial statement analysis indicate a positive revenue outlook based on existing assets and liabilities[^3].\n",
      "\n",
      "## References\n",
      "- [^1]: shsconf_icdeba2023_02022.pdf [page 4]\n",
      "- [^2]: shsconf_icdeba2023_02022.pdf [page 4]\n",
      "- [^3]: shsconf_icdeba2023_02022.pdf [page 0]\n",
      "Log: \n",
      "Invoking: `write_file` with `{'file_path': 'report.md', 'text': \"## Summary of Tesla's Financial Information and Revenue Outlook\\n\\n- Tesla's revenue from electric vehicle sales is projected to reach about $130 billion by 2025, an 80% increase from 2022[^1].\\n- The forecasted profit for Tesla is $71.4 billion in 2023, $84.6 billion in 2024, and $131.2 billion in 2025[^2].\\n- The number of vehicle sales is expected to reach 1.8 million units in 2023, approximately a 35% year-on-year increase[^2].\\n- Tesla's business model and financial statement analysis indicate a positive revenue outlook based on existing assets and liabilities[^3].\\n\\n## References\\n- [^1]: shsconf_icdeba2023_02022.pdf [page 4]\\n- [^2]: shsconf_icdeba2023_02022.pdf [page 4]\\n- [^3]: shsconf_icdeba2023_02022.pdf [page 0]\"}`\n",
      "\n",
      "\n",
      "\n",
      "[Observation]\n",
      "Observation: File written successfully to report.md.\n",
      "[Tool Called]\n",
      "Tool: tavily_search_results_json\n",
      "query: Tesla revenue outlook 2024-2025\n",
      "Log: \n",
      "Invoking: `tavily_search_results_json` with `{'query': 'Tesla revenue outlook 2024-2025'}`\n",
      "\n",
      "\n",
      "\n",
      "[Observation]\n",
      "Observation: [{'url': 'https://finance.yahoo.com/news/tesla-stock-rises-after-company-pledges-return-to-growth-after-q4-results-disappoint-230732196.html', 'content': 'Tesla (TSLA) stock rose 4% in extended trading on Wednesday after the company pledged a return to growth in 2025 after fourth quarter results disappointed to cap off a year that saw revenue rise just 1% while profits fell sharply from a year ago. In its shareholder presentation, Tesla said it expects its auto business to return to growth in 2025 after total auto revenues fell 8% in the fourth quarter against last year and 6% in 2024 compared to 2023. Tesla said vehicle volume this year is expected to return to growth due to advancements in vehicle autonomy and the launch of new products. Read the latest financial and business news from Yahoo Finance'}, {'url': 'https://ir.tesla.com/press-release/tesla-fourth-quarter-2024-production-deliveries-and-deployments', 'content': 'Tesla Fourth Quarter 2024 Production, Deliveries & Deployments Tesla will post its financial results for the fourth quarter of 2024 after market close on Wednesday, January 29, 2025. Tesla management will hold a live question and answer webcast that day at 4:30 p.m. Central Time (5:30 p.m. Eastern Time) to discuss the Company’s financial and business results and outlook. What:\\xa0Tesla Q4 2024 Financial Results and Q&A Webcast Q4 2024 Update:\\xa0https://ir.tesla.com Tesla vehicle deliveries and storage deployments represent only two measures of the Company’s financial performance and should not be relied on as an indicator of quarterly financial results, which depend on a variety of factors, including average selling price, cost of sales, foreign exchange movements and others as to be disclosed in the 10-K for the year ended on December 31, 2024.'}, {'url': 'https://www.investopedia.com/tesla-earnings-q4-fy2024-elon-musk-conference-call-fsd-8780773', 'content': 'Tesla (TSLA) reported fourth-quarter revenue and adjusted profit below analysts\\' estimates late Wednesday, with the stock first falling and then rising in after-hours trading after the company\\'s report and conference call. Tesla\\'s shares, which first fell on the earnings news, were up about 4% after the conference call ended. Tesla said its Full Self-Driving technology \"continues to rapidly improve,\" with the company working to launch the supervised version of the software in Europe and China sometime this year. CEO Elon Musk said during Wednesday\\'s call that the company plans to start using the unsupervised version of the self-driving software with Tesla vehicles at the company\\'s Austin, Texas mfactory starting in June, with a broader public release possible this year. This article story has been updated with the latest share price information and details from Tesla\\'s earnings presentation and conference call.'}, {'url': 'https://www.cnbc.com/2025/01/29/tesla-tsla-2024-q4-earnings.html', 'content': \"Best Credit Cards Best Loans to Refinance Credit Card Debt Best Money Market Accounts Best Credit Cards for Small Business Best Personal Loans for Bad Credit Best Mortgages for Bad Credit Best Investing Apps Tesla set to report fourth-quarter earnings after the bell Tesla reports fourth-quarter results after the bell following a dramatic rally in the company's stock price to end the year. Tesla's earnings report follows a steep rally in the company's stock price tied to the election of President Donald Trump. As CNBC previously reported, Tesla's brand value shed $15 billion in 2024, owing to multiple factors including the company's aging lineup of EVs, and Musk's incendiary political rhetoric and conduct, according to research by Brand Finance. About CNBC\"}, {'url': 'https://www.nytimes.com/2025/01/29/business/tesla-earnings-elon-musk.html', 'content': 'Tesla’s Profit Fell Sharply Last Year The company, which is led by Elon Musk, said it made a profit of $2.3 billion during the last three months of 2024. That was a decline compared with $7.9 billion a year earlier, but 2023’s profit included a one-time tax benefit of $5.9 billion. Tesla’s operating profit, which excludes that special gain, fell 23 percent in the final three months of the year. A year earlier, the company generated $433 million from such sales. For the full year, profit was $7.1 billion, Tesla said, down from $15 billion a year earlier. If you are in Reader mode please exit and\\xa0log into\\xa0your Times account, or\\xa0subscribe\\xa0for all of The Times.'}]\n",
      "[Tool Called]\n",
      "Tool: write_file\n",
      "file_path: report.md\n",
      "text: \n",
      "\n",
      "## Web Search Results on Tesla's Revenue Outlook\n",
      "\n",
      "- Tesla expects its auto business to return to growth in 2025 after a decline in total auto revenues in 2024[^4].\n",
      "- The company plans to leverage advancements in vehicle autonomy and new product launches to boost vehicle volume[^4].\n",
      "- Tesla's Full Self-Driving technology is expected to improve, with plans for broader public release[^5].\n",
      "- Tesla's profit fell sharply in 2024, with a full-year profit of $7.1 billion, down from $15 billion in 2023[^6].\n",
      "\n",
      "## References\n",
      "- [^1]: shsconf_icdeba2023_02022.pdf [page 4]\n",
      "- [^2]: shsconf_icdeba2023_02022.pdf [page 4]\n",
      "- [^3]: shsconf_icdeba2023_02022.pdf [page 0]\n",
      "- [^4]: finance.yahoo.com [link](https://finance.yahoo.com/news/tesla-stock-rises-after-company-pledges-return-to-growth-after-q4-results-disappoint-230732196.html)\n",
      "- [^5]: investopedia.com [link](https://www.investopedia.com/tesla-earnings-q4-fy2024-elon-musk-conference-call-fsd-8780773)\n",
      "- [^6]: nytimes.com [link](https://www.nytimes.com/2025/01/29/business/tesla-earnings-elon-musk.html)\n",
      "Log: \n",
      "Invoking: `write_file` with `{'file_path': 'report.md', 'text': \"\\n\\n## Web Search Results on Tesla's Revenue Outlook\\n\\n- Tesla expects its auto business to return to growth in 2025 after a decline in total auto revenues in 2024[^4].\\n- The company plans to leverage advancements in vehicle autonomy and new product launches to boost vehicle volume[^4].\\n- Tesla's Full Self-Driving technology is expected to improve, with plans for broader public release[^5].\\n- Tesla's profit fell sharply in 2024, with a full-year profit of $7.1 billion, down from $15 billion in 2023[^6].\\n\\n## References\\n- [^1]: shsconf_icdeba2023_02022.pdf [page 4]\\n- [^2]: shsconf_icdeba2023_02022.pdf [page 4]\\n- [^3]: shsconf_icdeba2023_02022.pdf [page 0]\\n- [^4]: finance.yahoo.com [link](https://finance.yahoo.com/news/tesla-stock-rises-after-company-pledges-return-to-growth-after-q4-results-disappoint-230732196.html)\\n- [^5]: investopedia.com [link](https://www.investopedia.com/tesla-earnings-q4-fy2024-elon-musk-conference-call-fsd-8780773)\\n- [^6]: nytimes.com [link](https://www.nytimes.com/2025/01/29/business/tesla-earnings-elon-musk.html)\"}`\n",
      "\n",
      "\n",
      "\n",
      "[Observation]\n",
      "Observation: File written successfully to report.md.\n",
      "[Tool Called]\n",
      "Tool: read_file\n",
      "file_path: report.md\n",
      "Log: \n",
      "Invoking: `read_file` with `{'file_path': 'report.md'}`\n",
      "\n",
      "\n",
      "\n",
      "[Observation]\n",
      "Observation: \n",
      "\n",
      "## Web Search Results on Tesla's Revenue Outlook\n",
      "\n",
      "- Tesla expects its auto business to return to growth in 2025 after a decline in total auto revenues in 2024[^4].\n",
      "- The company plans to leverage advancements in vehicle autonomy and new product launches to boost vehicle volume[^4].\n",
      "- Tesla's Full Self-Driving technology is expected to improve, with plans for broader public release[^5].\n",
      "- Tesla's profit fell sharply in 2024, with a full-year profit of $7.1 billion, down from $15 billion in 2023[^6].\n",
      "\n",
      "## References\n",
      "- [^1]: shsconf_icdeba2023_02022.pdf [page 4]\n",
      "- [^2]: shsconf_icdeba2023_02022.pdf [page 4]\n",
      "- [^3]: shsconf_icdeba2023_02022.pdf [page 0]\n",
      "- [^4]: finance.yahoo.com [link](https://finance.yahoo.com/news/tesla-stock-rises-after-company-pledges-return-to-growth-after-q4-results-disappoint-230732196.html)\n",
      "- [^5]: investopedia.com [link](https://www.investopedia.com/tesla-earnings-q4-fy2024-elon-musk-conference-call-fsd-8780773)\n",
      "- [^6]: nytimes.com [link](https://www.nytimes.com/2025/01/29/business/tesla-earnings-elon-musk.html)\n",
      "[Tool Called]\n",
      "Tool: read_file\n",
      "file_path: report.md\n",
      "Log: \n",
      "Invoking: `read_file` with `{'file_path': 'report.md'}`\n",
      "\n",
      "\n",
      "\n",
      "[Observation]\n",
      "Observation: \n",
      "\n",
      "## Web Search Results on Tesla's Revenue Outlook\n",
      "\n",
      "- Tesla expects its auto business to return to growth in 2025 after a decline in total auto revenues in 2024[^4].\n",
      "- The company plans to leverage advancements in vehicle autonomy and new product launches to boost vehicle volume[^4].\n",
      "- Tesla's Full Self-Driving technology is expected to improve, with plans for broader public release[^5].\n",
      "- Tesla's profit fell sharply in 2024, with a full-year profit of $7.1 billion, down from $15 billion in 2023[^6].\n",
      "\n",
      "## References\n",
      "- [^1]: shsconf_icdeba2023_02022.pdf [page 4]\n",
      "- [^2]: shsconf_icdeba2023_02022.pdf [page 4]\n",
      "- [^3]: shsconf_icdeba2023_02022.pdf [page 0]\n",
      "- [^4]: finance.yahoo.com [link](https://finance.yahoo.com/news/tesla-stock-rises-after-company-pledges-return-to-growth-after-q4-results-disappoint-230732196.html)\n",
      "- [^5]: investopedia.com [link](https://www.investopedia.com/tesla-earnings-q4-fy2024-elon-musk-conference-call-fsd-8780773)\n",
      "- [^6]: nytimes.com [link](https://www.nytimes.com/2025/01/29/business/tesla-earnings-elon-musk.html)\n",
      "[Tool Called]\n",
      "Tool: write_file\n",
      "file_path: report_final.md\n",
      "text: ![Company Future](https://example.com/your_image.png)\n",
      "\n",
      "## Overview\n",
      "Tesla's financial outlook for 2024-2025 shows a mixed performance with expected growth in vehicle sales and advancements in technology, despite a decline in profits in 2024. The company aims to leverage new product launches and improved vehicle autonomy to boost revenue.\n",
      "\n",
      "## Key Points\n",
      "- Tesla's revenue from electric vehicle sales is projected to reach about $130 billion by 2025, an 80% increase from 2022[^1].\n",
      "- The forecasted profit for Tesla is $71.4 billion in 2023, $84.6 billion in 2024, and $131.2 billion in 2025[^2].\n",
      "- The number of vehicle sales is expected to reach 1.8 million units in 2023, approximately a 35% year-on-year increase[^2].\n",
      "- Tesla's business model and financial statement analysis indicate a positive revenue outlook based on existing assets and liabilities[^3].\n",
      "- Tesla expects its auto business to return to growth in 2025 after a decline in total auto revenues in 2024[^4].\n",
      "- The company plans to leverage advancements in vehicle autonomy and new product launches to boost vehicle volume[^4].\n",
      "- Tesla's Full Self-Driving technology is expected to improve, with plans for broader public release[^5].\n",
      "- Tesla's profit fell sharply in 2024, with a full-year profit of $7.1 billion, down from $15 billion in 2023[^6].\n",
      "\n",
      "## Conclusion\n",
      "Tesla's financial outlook for 2024-2025 is characterized by a strategic focus on growth through technological advancements and new product offerings. Despite a challenging year in 2024, the company is poised for a rebound in 2025, driven by increased vehicle sales and improved autonomous driving capabilities.\n",
      "\n",
      "## References\n",
      "- [^1]: shsconf_icdeba2023_02022.pdf [page 4]\n",
      "- [^2]: shsconf_icdeba2023_02022.pdf [page 4]\n",
      "- [^3]: shsconf_icdeba2023_02022.pdf [page 0]\n",
      "- [^4]: finance.yahoo.com [link](https://finance.yahoo.com/news/tesla-stock-rises-after-company-pledges-return-to-growth-after-q4-results-disappoint-230732196.html)\n",
      "- [^5]: investopedia.com [link](https://www.investopedia.com/tesla-earnings-q4-fy2024-elon-musk-conference-call-fsd-8780773)\n",
      "- [^6]: nytimes.com [link](https://www.nytimes.com/2025/01/29/business/tesla-earnings-elon-musk.html)\n",
      "Log: \n",
      "Invoking: `write_file` with `{'file_path': 'report_final.md', 'text': \"![Company Future](https://example.com/your_image.png)\\n\\n## Overview\\nTesla's financial outlook for 2024-2025 shows a mixed performance with expected growth in vehicle sales and advancements in technology, despite a decline in profits in 2024. The company aims to leverage new product launches and improved vehicle autonomy to boost revenue.\\n\\n## Key Points\\n- Tesla's revenue from electric vehicle sales is projected to reach about $130 billion by 2025, an 80% increase from 2022[^1].\\n- The forecasted profit for Tesla is $71.4 billion in 2023, $84.6 billion in 2024, and $131.2 billion in 2025[^2].\\n- The number of vehicle sales is expected to reach 1.8 million units in 2023, approximately a 35% year-on-year increase[^2].\\n- Tesla's business model and financial statement analysis indicate a positive revenue outlook based on existing assets and liabilities[^3].\\n- Tesla expects its auto business to return to growth in 2025 after a decline in total auto revenues in 2024[^4].\\n- The company plans to leverage advancements in vehicle autonomy and new product launches to boost vehicle volume[^4].\\n- Tesla's Full Self-Driving technology is expected to improve, with plans for broader public release[^5].\\n- Tesla's profit fell sharply in 2024, with a full-year profit of $7.1 billion, down from $15 billion in 2023[^6].\\n\\n## Conclusion\\nTesla's financial outlook for 2024-2025 is characterized by a strategic focus on growth through technological advancements and new product offerings. Despite a challenging year in 2024, the company is poised for a rebound in 2025, driven by increased vehicle sales and improved autonomous driving capabilities.\\n\\n## References\\n- [^1]: shsconf_icdeba2023_02022.pdf [page 4]\\n- [^2]: shsconf_icdeba2023_02022.pdf [page 4]\\n- [^3]: shsconf_icdeba2023_02022.pdf [page 0]\\n- [^4]: finance.yahoo.com [link](https://finance.yahoo.com/news/tesla-stock-rises-after-company-pledges-return-to-growth-after-q4-results-disappoint-230732196.html)\\n- [^5]: investopedia.com [link](https://www.investopedia.com/tesla-earnings-q4-fy2024-elon-musk-conference-call-fsd-8780773)\\n- [^6]: nytimes.com [link](https://www.nytimes.com/2025/01/29/business/tesla-earnings-elon-musk.html)\"}`\n",
      "\n",
      "\n",
      "\n",
      "[Observation]\n",
      "Observation: File written successfully to report_final.md.\n",
      "[Tool Called]\n",
      "Tool: pdf_search\n",
      "query: Tesla financial information and revenue outlook 2024-2025\n",
      "Log: \n",
      "Invoking: `pdf_search` with `{'query': 'Tesla financial information and revenue outlook 2024-2025'}`\n",
      "\n",
      "\n",
      "\n",
      "[Tool Called]\n",
      "Tool: tavily_search_results_json\n",
      "query: Tesla revenue outlook 2024-2025\n",
      "Log: \n",
      "Invoking: `tavily_search_results_json` with `{'query': 'Tesla revenue outlook 2024-2025'}`\n",
      "\n",
      "\n",
      "\n",
      "[Observation]\n",
      "Observation: <document>\n",
      "  <content>dollars, +18% year-on-year. Assuming a vehicle price of \n",
      "$45,000 and $43,000 in 24 and '25, by 2025, the revenue \n",
      "from electric vehicle sales will be about $130 billion, +80% \n",
      "from '22. All of this is based on an analysis of Tesla's \n",
      "existing assets and liabilities and business model. This study \n",
      "predicts Tesla's income in the next few years. It is certain \n",
      "that Tesla's income will continue to grow in the next few \n",
      "years, which may help some investors related to Tesla in \n",
      "terms of investment. However, since Tesla discloses less \n",
      "economic information to the outside world, and the research \n",
      "method of this paper is relatively simple, the information \n",
      "that can be provided is limited. In future studies, researchers \n",
      "can use more diverse and accurate methods to predict \n",
      "Tesla's income. \n",
      "References \n",
      "1. Y. Liu, Jiangsu Comm Forum 369, 7 (2015) \n",
      "2. F. Han, Beijing Uni Posts Telec, (2018) \n",
      "3. S. Yan, Modern Busi 589, 36 (2020) \n",
      "4. M. Wang, Shandong Uni, (2021)</content>\n",
      "  <page>4</page>\n",
      "  <source>shsconf_icdeba2023_02022.pdf</source>\n",
      "</document>\n",
      "\n",
      "<document>\n",
      "  <content>strategy of the company's development. Similarly, gross \n",
      "margin will fluctuate with changes in capacity, sales volume, \n",
      "scale effect, and amortized production costs.. \n",
      "In 2020, Tesla produced a total of 1,369,600 vehicles \n",
      "worldwide and delivered a total of 1,313,900 vehicles, +40% \n",
      "year-on-year, slightly below the 50% growth target set at the \n",
      "beginning of 22 years. \n",
      "Number of vehicle sales are expected to reach 1.8 \n",
      "million units in 23 years, approximately +35% y/y. \n",
      "Combined with a forecast for the number of Tesla electric \n",
      "vehicle deliveries, we can predict Tesla's future revenue. \n",
      "6 Conclusion \n",
      "Fig. 1. Revenue forecast. \n",
      "Figure 1 shows Tesla's future revenue. So, Tesla's forecast \n",
      "profit is $71.4 billion in 2023, $84.6 billion in 2024, and \n",
      "$131.2 billion in 2025. Based on the average price of Tesla \n",
      "in 23 years of $47,000, the revenue of the electric vehicle \n",
      "business in 23 years is estimated to be 84.6 billion US \n",
      "dollars, +18% year-on-year. Assuming a vehicle price of</content>\n",
      "  <page>4</page>\n",
      "  <source>shsconf_icdeba2023_02022.pdf</source>\n",
      "</document>\n",
      "\n",
      "<document>\n",
      "  <content>Corresponding author: 1910741120@mail.sit.edu.cn \n",
      "year. With a penetration rate of 2.1%, the global sales \n",
      "volume of automobiles in 2018 exceeded 2 million. China, \n",
      "the USA, Germany, France, Sweden, Japan, and other \n",
      "nations account for a large portion of the world's new energy \n",
      "market [3]. If you want to predict the future development of \n",
      "the electric vehicle industry, you can speculate by predicting \n",
      "Tesla's future financial situation. This study hopes to \n",
      "provide some insight into the future forecast of the electric \n",
      "vehicle industry by predicting Tesla's future financial \n",
      "situation. In this research, common-size financial statements \n",
      "and ratio analysis are used. Start with Tesla's basic financial \n",
      "situation, then analyze Tesla's business model, and finally \n",
      "predict Tesla's future financial situation. \n",
      "2 An analysis of Tesla's underlying \n",
      "financial position \n",
      "2.1 Assets \n",
      " \n",
      " \n",
      " \n",
      "SHS Web of Conferences 181, 02022 (2024)\t\n",
      "https://doi.org/10.1051/shsconf/202418102022\n",
      "ICDEBA 2023</content>\n",
      "  <page>0</page>\n",
      "  <source>shsconf_icdeba2023_02022.pdf</source>\n",
      "</document>\n",
      "\n",
      "<document>\n",
      "  <content>Tesla's revenue forecast base on business model and financial \n",
      "statement analysis \n",
      "Chenhao Fang   \n",
      "Intelligent Accounting Management Institute, Guangdong University of Finance and Economics, 510200 Guangzhou, China \n",
      "Abstract. With the rapid development of the electric vehicle industry, Tesla, as the benchmark of this industry, \n",
      "has been studied by many companies in the same industry and investors outside the industry. Based on Tesla's \n",
      "financial reports in recent years and news about Tesla, Tesla's assets, liabilities, and owner's equity are analyzed \n",
      "to analyze Tesla's basic financial situation, from this, it can be concluded that Tesla's asset-liability ratio and \n",
      "other financial trends have changed in recent years. Then analyze Tesla's business model from the aspects of \n",
      "corporate positioning, business type, and profit model, so, in recent years, Tesla's main profit models, income</content>\n",
      "  <page>0</page>\n",
      "  <source>shsconf_icdeba2023_02022.pdf</source>\n",
      "</document>\n",
      "[Observation]\n",
      "Observation: [{'url': 'https://finance.yahoo.com/news/tesla-stock-rises-after-company-pledges-return-to-growth-after-q4-results-disappoint-230732196.html', 'content': 'Tesla (TSLA) stock rose 4% in extended trading on Wednesday after the company pledged a return to growth in 2025 after fourth quarter results disappointed to cap off a year that saw revenue rise just 1% while profits fell sharply from a year ago. In its shareholder presentation, Tesla said it expects its auto business to return to growth in 2025 after total auto revenues fell 8% in the fourth quarter against last year and 6% in 2024 compared to 2023. Tesla said vehicle volume this year is expected to return to growth due to advancements in vehicle autonomy and the launch of new products. Read the latest financial and business news from Yahoo Finance'}, {'url': 'https://ir.tesla.com/press-release/tesla-fourth-quarter-2024-production-deliveries-and-deployments', 'content': 'Tesla Fourth Quarter 2024 Production, Deliveries & Deployments Tesla will post its financial results for the fourth quarter of 2024 after market close on Wednesday, January 29, 2025. Tesla management will hold a live question and answer webcast that day at 4:30 p.m. Central Time (5:30 p.m. Eastern Time) to discuss the Company’s financial and business results and outlook. What:\\xa0Tesla Q4 2024 Financial Results and Q&A Webcast Q4 2024 Update:\\xa0https://ir.tesla.com Tesla vehicle deliveries and storage deployments represent only two measures of the Company’s financial performance and should not be relied on as an indicator of quarterly financial results, which depend on a variety of factors, including average selling price, cost of sales, foreign exchange movements and others as to be disclosed in the 10-K for the year ended on December 31, 2024.'}, {'url': 'https://www.investopedia.com/tesla-earnings-q4-fy2024-elon-musk-conference-call-fsd-8780773', 'content': 'Tesla (TSLA) reported fourth-quarter revenue and adjusted profit below analysts\\' estimates late Wednesday, with the stock first falling and then rising in after-hours trading after the company\\'s report and conference call. Tesla\\'s shares, which first fell on the earnings news, were up about 4% after the conference call ended. Tesla said its Full Self-Driving technology \"continues to rapidly improve,\" with the company working to launch the supervised version of the software in Europe and China sometime this year. CEO Elon Musk said during Wednesday\\'s call that the company plans to start using the unsupervised version of the self-driving software with Tesla vehicles at the company\\'s Austin, Texas mfactory starting in June, with a broader public release possible this year. This article story has been updated with the latest share price information and details from Tesla\\'s earnings presentation and conference call.'}, {'url': 'https://www.cnbc.com/2025/01/29/tesla-tsla-2024-q4-earnings.html', 'content': \"Best Credit Cards Best Loans to Refinance Credit Card Debt Best Money Market Accounts Best Credit Cards for Small Business Best Personal Loans for Bad Credit Best Mortgages for Bad Credit Best Investing Apps Tesla set to report fourth-quarter earnings after the bell Tesla reports fourth-quarter results after the bell following a dramatic rally in the company's stock price to end the year. Tesla's earnings report follows a steep rally in the company's stock price tied to the election of President Donald Trump. As CNBC previously reported, Tesla's brand value shed $15 billion in 2024, owing to multiple factors including the company's aging lineup of EVs, and Musk's incendiary political rhetoric and conduct, according to research by Brand Finance. About CNBC\"}, {'url': 'https://www.nytimes.com/2025/01/29/business/tesla-earnings-elon-musk.html', 'content': 'Tesla’s Profit Fell Sharply Last Year The company, which is led by Elon Musk, said it made a profit of $2.3 billion during the last three months of 2024. That was a decline compared with $7.9 billion a year earlier, but 2023’s profit included a one-time tax benefit of $5.9 billion. Tesla’s operating profit, which excludes that special gain, fell 23 percent in the final three months of the year. A year earlier, the company generated $433 million from such sales. For the full year, profit was $7.1 billion, Tesla said, down from $15 billion a year earlier. If you are in Reader mode please exit and\\xa0log into\\xa0your Times account, or\\xa0subscribe\\xa0for all of The Times.'}]\n",
      "[Tool Called]\n",
      "Tool: dalle_tool\n",
      "query: Tesla future outlook with electric vehicles and autonomous technology\n",
      "Log: \n",
      "Invoking: `dalle_tool` with `{'query': 'Tesla future outlook with electric vehicles and autonomous technology'}`\n",
      "\n",
      "\n",
      "\n",
      "[Observation]\n",
      "Observation: https://oaidalleapiprodscus.blob.core.windows.net/private/org-cklzgJgdr1X4aNqRAAPddNfR/user-UJN3VEkv67JiO9Mm1aeNBkBJ/img-KzacujKvTzKwguFWhDRUPPR3.png?st=2025-02-12T06%3A14%3A46Z&se=2025-02-12T08%3A14%3A46Z&sp=r&sv=2024-08-04&sr=b&rscd=inline&rsct=image/png&skoid=d505667d-d6c1-4a0a-bac7-5c84a87759f8&sktid=a48cca56-e6da-484e-a814-9c849652bcb3&skt=2025-02-12T04%3A30%3A56Z&ske=2025-02-13T04%3A30%3A56Z&sks=b&skv=2024-08-04&sig=bFohqVKOpkqcGb6AY/kKsfsPKUMO9JkT%2BmDkYw/3tJM%3D\n",
      "[Tool Called]\n",
      "Tool: read_file\n",
      "file_path: report_final.md\n",
      "Log: \n",
      "Invoking: `read_file` with `{'file_path': 'report_final.md'}`\n",
      "\n",
      "\n",
      "\n",
      "[Observation]\n",
      "Observation: ![Company Future](https://example.com/your_image.png)\n",
      "\n",
      "## Overview\n",
      "Tesla's financial outlook for 2024-2025 shows a mixed performance with expected growth in vehicle sales and advancements in technology, despite a decline in profits in 2024. The company aims to leverage new product launches and improved vehicle autonomy to boost revenue.\n",
      "\n",
      "## Key Points\n",
      "- Tesla's revenue from electric vehicle sales is projected to reach about $130 billion by 2025, an 80% increase from 2022[^1].\n",
      "- The forecasted profit for Tesla is $71.4 billion in 2023, $84.6 billion in 2024, and $131.2 billion in 2025[^2].\n",
      "- The number of vehicle sales is expected to reach 1.8 million units in 2023, approximately a 35% year-on-year increase[^2].\n",
      "- Tesla's business model and financial statement analysis indicate a positive revenue outlook based on existing assets and liabilities[^3].\n",
      "- Tesla expects its auto business to return to growth in 2025 after a decline in total auto revenues in 2024[^4].\n",
      "- The company plans to leverage advancements in vehicle autonomy and new product launches to boost vehicle volume[^4].\n",
      "- Tesla's Full Self-Driving technology is expected to improve, with plans for broader public release[^5].\n",
      "- Tesla's profit fell sharply in 2024, with a full-year profit of $7.1 billion, down from $15 billion in 2023[^6].\n",
      "\n",
      "## Conclusion\n",
      "Tesla's financial outlook for 2024-2025 is characterized by a strategic focus on growth through technological advancements and new product offerings. Despite a challenging year in 2024, the company is poised for a rebound in 2025, driven by increased vehicle sales and improved autonomous driving capabilities.\n",
      "\n",
      "## References\n",
      "- [^1]: shsconf_icdeba2023_02022.pdf [page 4]\n",
      "- [^2]: shsconf_icdeba2023_02022.pdf [page 4]\n",
      "- [^3]: shsconf_icdeba2023_02022.pdf [page 0]\n",
      "- [^4]: finance.yahoo.com [link](https://finance.yahoo.com/news/tesla-stock-rises-after-company-pledges-return-to-growth-after-q4-results-disappoint-230732196.html)\n",
      "- [^5]: investopedia.com [link](https://www.investopedia.com/tesla-earnings-q4-fy2024-elon-musk-conference-call-fsd-8780773)\n",
      "- [^6]: nytimes.com [link](https://www.nytimes.com/2025/01/29/business/tesla-earnings-elon-musk.html)\n",
      "[Tool Called]\n",
      "Tool: write_file\n",
      "file_path: report_final.md\n",
      "text: ![Company Future](https://oaidalleapiprodscus.blob.core.windows.net/private/org-cklzgJgdr1X4aNqRAAPddNfR/user-UJN3VEkv67JiO9Mm1aeNBkBJ/img-KzacujKvTzKwguFWhDRUPPR3.png?st=2025-02-12T06%3A14%3A46Z&se=2025-02-12T08%3A14%3A46Z&sp=r&sv=2024-08-04&sr=b&rscd=inline&rsct=image/png&skoid=d505667d-d6c1-4a0a-bac7-5c84a87759f8&sktid=a48cca56-e6da-484e-a814-9c849652bcb3&skt=2025-02-12T04%3A30%3A56Z&ske=2025-02-13T04%3A30%3A56Z&sks=b&skv=2024-08-04&sig=bFohqVKOpkqcGb6AY/kKsfsPKUMO9JkT%2BmDkYw/3tJM%3D)\n",
      "\n",
      "## Overview\n",
      "Tesla's financial outlook for 2024-2025 shows a mixed performance with expected growth in vehicle sales and advancements in technology, despite a decline in profits in 2024. The company aims to leverage new product launches and improved vehicle autonomy to boost revenue.\n",
      "\n",
      "## Key Points\n",
      "- Tesla's revenue from electric vehicle sales is projected to reach about $130 billion by 2025, an 80% increase from 2022[^1].\n",
      "- The forecasted profit for Tesla is $71.4 billion in 2023, $84.6 billion in 2024, and $131.2 billion in 2025[^2].\n",
      "- The number of vehicle sales is expected to reach 1.8 million units in 2023, approximately a 35% year-on-year increase[^2].\n",
      "- Tesla's business model and financial statement analysis indicate a positive revenue outlook based on existing assets and liabilities[^3].\n",
      "- Tesla expects its auto business to return to growth in 2025 after a decline in total auto revenues in 2024[^4].\n",
      "- The company plans to leverage advancements in vehicle autonomy and new product launches to boost vehicle volume[^4].\n",
      "- Tesla's Full Self-Driving technology is expected to improve, with plans for broader public release[^5].\n",
      "- Tesla's profit fell sharply in 2024, with a full-year profit of $7.1 billion, down from $15 billion in 2023[^6].\n",
      "\n",
      "## Conclusion\n",
      "Tesla's financial outlook for 2024-2025 is characterized by a strategic focus on growth through technological advancements and new product offerings. Despite a challenging year in 2024, the company is poised for a rebound in 2025, driven by increased vehicle sales and improved autonomous driving capabilities.\n",
      "\n",
      "## References\n",
      "- [^1]: shsconf_icdeba2023_02022.pdf [page 4]\n",
      "- [^2]: shsconf_icdeba2023_02022.pdf [page 4]\n",
      "- [^3]: shsconf_icdeba2023_02022.pdf [page 0]\n",
      "- [^4]: finance.yahoo.com [link](https://finance.yahoo.com/news/tesla-stock-rises-after-company-pledges-return-to-growth-after-q4-results-disappoint-230732196.html)\n",
      "- [^5]: investopedia.com [link](https://www.investopedia.com/tesla-earnings-q4-fy2024-elon-musk-conference-call-fsd-8780773)\n",
      "- [^6]: nytimes.com [link](https://www.nytimes.com/2025/01/29/business/tesla-earnings-elon-musk.html)\n",
      "Log: \n",
      "Invoking: `write_file` with `{'file_path': 'report_final.md', 'text': \"![Company Future](https://oaidalleapiprodscus.blob.core.windows.net/private/org-cklzgJgdr1X4aNqRAAPddNfR/user-UJN3VEkv67JiO9Mm1aeNBkBJ/img-KzacujKvTzKwguFWhDRUPPR3.png?st=2025-02-12T06%3A14%3A46Z&se=2025-02-12T08%3A14%3A46Z&sp=r&sv=2024-08-04&sr=b&rscd=inline&rsct=image/png&skoid=d505667d-d6c1-4a0a-bac7-5c84a87759f8&sktid=a48cca56-e6da-484e-a814-9c849652bcb3&skt=2025-02-12T04%3A30%3A56Z&ske=2025-02-13T04%3A30%3A56Z&sks=b&skv=2024-08-04&sig=bFohqVKOpkqcGb6AY/kKsfsPKUMO9JkT%2BmDkYw/3tJM%3D)\\n\\n## Overview\\nTesla's financial outlook for 2024-2025 shows a mixed performance with expected growth in vehicle sales and advancements in technology, despite a decline in profits in 2024. The company aims to leverage new product launches and improved vehicle autonomy to boost revenue.\\n\\n## Key Points\\n- Tesla's revenue from electric vehicle sales is projected to reach about $130 billion by 2025, an 80% increase from 2022[^1].\\n- The forecasted profit for Tesla is $71.4 billion in 2023, $84.6 billion in 2024, and $131.2 billion in 2025[^2].\\n- The number of vehicle sales is expected to reach 1.8 million units in 2023, approximately a 35% year-on-year increase[^2].\\n- Tesla's business model and financial statement analysis indicate a positive revenue outlook based on existing assets and liabilities[^3].\\n- Tesla expects its auto business to return to growth in 2025 after a decline in total auto revenues in 2024[^4].\\n- The company plans to leverage advancements in vehicle autonomy and new product launches to boost vehicle volume[^4].\\n- Tesla's Full Self-Driving technology is expected to improve, with plans for broader public release[^5].\\n- Tesla's profit fell sharply in 2024, with a full-year profit of $7.1 billion, down from $15 billion in 2023[^6].\\n\\n## Conclusion\\nTesla's financial outlook for 2024-2025 is characterized by a strategic focus on growth through technological advancements and new product offerings. Despite a challenging year in 2024, the company is poised for a rebound in 2025, driven by increased vehicle sales and improved autonomous driving capabilities.\\n\\n## References\\n- [^1]: shsconf_icdeba2023_02022.pdf [page 4]\\n- [^2]: shsconf_icdeba2023_02022.pdf [page 4]\\n- [^3]: shsconf_icdeba2023_02022.pdf [page 0]\\n- [^4]: finance.yahoo.com [link](https://finance.yahoo.com/news/tesla-stock-rises-after-company-pledges-return-to-growth-after-q4-results-disappoint-230732196.html)\\n- [^5]: investopedia.com [link](https://www.investopedia.com/tesla-earnings-q4-fy2024-elon-musk-conference-call-fsd-8780773)\\n- [^6]: nytimes.com [link](https://www.nytimes.com/2025/01/29/business/tesla-earnings-elon-musk.html)\"}`\n",
      "\n",
      "\n",
      "\n",
      "[Observation]\n",
      "Observation: File written successfully to report_final.md.\n",
      "[Final Answer]\n",
      "The comprehensive financial and market performance report for Tesla for the years 2024-2025 has been generated. Below is the complete content of the report:\n",
      "\n",
      "![Company Future](https://oaidalleapiprodscus.blob.core.windows.net/private/org-cklzgJgdr1X4aNqRAAPddNfR/user-UJN3VEkv67JiO9Mm1aeNBkBJ/img-KzacujKvTzKwguFWhDRUPPR3.png?st=2025-02-12T06%3A14%3A46Z&se=2025-02-12T08%3A14%3A46Z&sp=r&sv=2024-08-04&sr=b&rscd=inline&rsct=image/png&skoid=d505667d-d6c1-4a0a-bac7-5c84a87759f8&sktid=a48cca56-e6da-484e-a814-9c849652bcb3&skt=2025-02-12T04%3A30%3A56Z&ske=2025-02-13T04%3A30%3A56Z&sks=b&skv=2024-08-04&sig=bFohqVKOpkqcGb6AY/kKsfsPKUMO9JkT%2BmDkYw/3tJM%3D)\n",
      "\n",
      "## Overview\n",
      "Tesla's financial outlook for 2024-2025 shows a mixed performance with expected growth in vehicle sales and advancements in technology, despite a decline in profits in 2024. The company aims to leverage new product launches and improved vehicle autonomy to boost revenue.\n",
      "\n",
      "## Key Points\n",
      "- Tesla's revenue from electric vehicle sales is projected to reach about $130 billion by 2025, an 80% increase from 2022[^1].\n",
      "- The forecasted profit for Tesla is $71.4 billion in 2023, $84.6 billion in 2024, and $131.2 billion in 2025[^2].\n",
      "- The number of vehicle sales is expected to reach 1.8 million units in 2023, approximately a 35% year-on-year increase[^2].\n",
      "- Tesla's business model and financial statement analysis indicate a positive revenue outlook based on existing assets and liabilities[^3].\n",
      "- Tesla expects its auto business to return to growth in 2025 after a decline in total auto revenues in 2024[^4].\n",
      "- The company plans to leverage advancements in vehicle autonomy and new product launches to boost vehicle volume[^4].\n",
      "- Tesla's Full Self-Driving technology is expected to improve, with plans for broader public release[^5].\n",
      "- Tesla's profit fell sharply in 2024, with a full-year profit of $7.1 billion, down from $15 billion in 2023[^6].\n",
      "\n",
      "## Conclusion\n",
      "Tesla's financial outlook for 2024-2025 is characterized by a strategic focus on growth through technological advancements and new product offerings. Despite a challenging year in 2024, the company is poised for a rebound in 2025, driven by increased vehicle sales and improved autonomous driving capabilities.\n",
      "\n",
      "## References\n",
      "- [^1]: shsconf_icdeba2023_02022.pdf [page 4]\n",
      "- [^2]: shsconf_icdeba2023_02022.pdf [page 4]\n",
      "- [^3]: shsconf_icdeba2023_02022.pdf [page 0]\n",
      "- [^4]: finance.yahoo.com [link](https://finance.yahoo.com/news/tesla-stock-rises-after-company-pledges-return-to-growth-after-q4-results-disappoint-230732196.html)\n",
      "- [^5]: investopedia.com [link](https://www.investopedia.com/tesla-earnings-q4-fy2024-elon-musk-conference-call-fsd-8780773)\n",
      "- [^6]: nytimes.com [link](https://www.nytimes.com/2025/01/29/business/tesla-earnings-elon-musk.html)\n",
      "\n",
      "This report provides a detailed analysis of Tesla's financial and market performance, highlighting key areas of growth and challenges for the upcoming years.\n"
     ]
    }
   ],
   "source": [
    "# This cell asks the agent to summarize certain aspects of the Tesla PDF,\n",
    "# then writes them to 'report.md' and reads the file contents.\n",
    "\n",
    "query = \"Generate a comprehensive 2024-2025 financial and market performance report about Tesla.\"\n",
    "\n",
    "\n",
    "result = agent_with_chat_history.stream(\n",
    "    {\"input\": query}, config={\"configurable\": {\"session_id\": \"session_1\"}}\n",
    ")\n",
    "\n",
    "print(\"=== Agent Execution Result ===\")\n",
    "for step in result:\n",
    "    agent_stream_parser.process_agent_steps(step)"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "langchain-opentutorial-BpEVOGYk-py3.12",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.12.4"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
